<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="etcd," />





  <link rel="alternate" href="/blog/atom.xml" title="伏窗尾的猫" type="application/atom+xml" />






<meta name="description" content="前言新旅程的开始，学习etcd源码，旨在以项目为突破口精进go语言，了解更多设计思路。 raft算法raft算法将分布式存储的同步问题分解为了领袖选举（leader election）、日志复制（log replication）、安全性（safety）和成员关系变化（membership changes）这几个子问题。  领袖选举：领袖节点故障后，集群及时选举出新的领袖节点 日志复制：领袖节点从客">
<meta name="keywords" content="etcd">
<meta property="og:type" content="article">
<meta property="og:title" content="etcd源码阅读分析（一）">
<meta property="og:url" content="http://eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/index.html">
<meta property="og:site_name" content="伏窗尾的猫">
<meta property="og:description" content="前言新旅程的开始，学习etcd源码，旨在以项目为突破口精进go语言，了解更多设计思路。 raft算法raft算法将分布式存储的同步问题分解为了领袖选举（leader election）、日志复制（log replication）、安全性（safety）和成员关系变化（membership changes）这几个子问题。  领袖选举：领袖节点故障后，集群及时选举出新的领袖节点 日志复制：领袖节点从客">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/etcd源码阅读分析（一）/image-20210113001413169.png">
<meta property="og:image" content="http://eidolon_x.gitee.io/Users/lbin/workspace/hexo/source/_posts/etcd源码阅读分析（一）/image-20210113001413169.png">
<meta property="og:updated_time" content="2021-01-18T07:27:02.936Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="etcd源码阅读分析（一）">
<meta name="twitter:description" content="前言新旅程的开始，学习etcd源码，旨在以项目为突破口精进go语言，了解更多设计思路。 raft算法raft算法将分布式存储的同步问题分解为了领袖选举（leader election）、日志复制（log replication）、安全性（safety）和成员关系变化（membership changes）这几个子问题。  领袖选举：领袖节点故障后，集群及时选举出新的领袖节点 日志复制：领袖节点从客">
<meta name="twitter:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/etcd源码阅读分析（一）/image-20210113001413169.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/"/>





  <title>etcd源码阅读分析（一） | 伏窗尾的猫</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">伏窗尾的猫</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://eidolon_x.gitee.io/blog/blog/2020/12/17/etcd源码阅读分析（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="喵呜">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伏窗尾的猫">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">etcd源码阅读分析（一）</h1>
        

        <div class="post-meta">
		
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-17T00:36:20+08:00">
                2020-12-17
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2021-01-18T15:27:02+08:00">
                2021-01-18
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/etcd/" itemprop="url" rel="index">
                    <span itemprop="name">etcd</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/2020/12/17/etcd源码阅读分析（一）/" class="leancloud_visitors" data-flag-title="etcd源码阅读分析（一）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
				 <span>℃<span>
             </span>
          

          

		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
		  
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>新旅程的开始，学习etcd源码，旨在以项目为突破口精进go语言，了解更多设计思路。</p>
<h3 id="raft算法"><a href="#raft算法" class="headerlink" title="raft算法"></a>raft算法</h3><p>raft算法将分布式存储的同步问题分解为了领袖选举（leader election）、日志复制（log replication）、安全性（safety）和成员关系变化（membership changes）这几个子问题。</p>
<ul>
<li>领袖选举：领袖节点故障后，集群及时选举出新的领袖节点</li>
<li>日志复制：领袖节点从客户端接受操作，记录日志，并将日志复制到其他复制节点，并强制要求其他复制节点的日志必须和自己保持一致。</li>
<li>安全性（state machine safety）已提交的日志条目不应被覆盖更改，leader永远拥有最新的提交</li>
</ul>
<h4 id="领袖选举"><a href="#领袖选举" class="headerlink" title="领袖选举"></a>领袖选举</h4><p>raft使用非对称性选主模式，仅leader拥有决策权，同一时刻仅有一个主节点，并且客户端只与主节点进行交互。</p>
<p>raft包含leader，candidate，follower三种角色，描述三种角色的切换，当集群中不存在leader时，存储有全部已提交日志条目的follower成为能成为leader的candidate（不满足条件的candidate获取不到半数以上选票），candidate将本地的term+1，先投票给自己，然后广播requestVote rpc</p>
<table>
<thead>
<tr>
<th style="text-align:center">参数</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">term</td>
<td style="text-align:center">候选人的任期号</td>
</tr>
<tr>
<td style="text-align:center">candidateId</td>
<td style="text-align:center">请求投票的候选人id</td>
</tr>
<tr>
<td style="text-align:center">lastLogIndex</td>
<td style="text-align:center">候选人足心日志条目的索引</td>
</tr>
<tr>
<td style="text-align:center">lastLogTerm</td>
<td style="text-align:center">候选人最新日志对应的任期号</td>
</tr>
</tbody>
</table>
<p>通过返回值判断是否得到选票</p>
<table>
<thead>
<tr>
<th>返回值</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>当前任期号</td>
</tr>
<tr>
<td>voteGranted</td>
<td>是否得到选票</td>
</tr>
</tbody>
</table>
<p>此处选举重点</p>
<ul>
<li><p>一个term仅有一张选票</p>
</li>
<li><p>当发起者的term小于接受者本地最新的term（currentTerm），则接受者返回本地term，voteGranted位false，提醒候选人已经过期。</p>
</li>
<li>当发起者term大于接受者本地term（currentTerm），并且接受者没投票给任何人，或者已经投票给此发起者，并且此时发起者的日志与接受者的日志状态一致或更新（先判断任期号，再判断索引值，越大越新），则返回（term，true），否则还是返回（term，false）</li>
</ul>
<p>在此处保证了只有拥有最新提交的candidate才能晋升为leader，由于leader具有绝对的决策权，若leader错误，则集群整体错误。保证leader是拥有完整的正确提交，保证已提交的日志条目不被覆盖，确保安全性。</p>
<p>当某一candidate获取到半数以上选票时，candidate晋升为leader，但不是每一次选举都能选出leader，多个candidate存在均分选票的情况，此时candidate选举超时，进行下一次选举（item++），为避免无限循环的情况出现，candidate的选举超时随机（150ms-300ms），率先超时的节点会在其他节点超时时间赢得选举，成为leader。</p>
<h4 id="日志复制"><a href="#日志复制" class="headerlink" title="日志复制"></a>日志复制</h4><p>日志复制的顺序为：leader从客户端获取到请求，解析成指令后作为新的日志条目添加到本地，并并行发起AppendEntries  RPC，要求其他节点复制。当这些日志条目被安全复制（半数以上的rpc返回true），此时认为此日志条目已提交，leader此时会应用此日志条目到状态机，并返回客户端。如果fallower崩溃或运行缓慢，leader会不停尝试发送rpc，直到全部存储，当跟随者发现日志条目被提交后，他也将这个日志条目应用到本地的状态机中，实现同步。</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>领导人任期</td>
</tr>
<tr>
<td>leaderId</td>
<td>领导人id（用于其他节点重定向客户端请求）</td>
</tr>
<tr>
<td>prevLogIndex</td>
<td>领导人最新日志前一位置的索引</td>
</tr>
<tr>
<td>prevLogTerm</td>
<td>领导人最新日志前一位置的任期</td>
</tr>
<tr>
<td>Entries[]</td>
<td>需要追加的日志条目，心跳包时为空</td>
</tr>
<tr>
<td>leaderCommit</td>
<td>领导人已知已提交最高的日志条目索引</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>返回值</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>本地term与发起者的term中较大值</td>
</tr>
<tr>
<td>success</td>
<td>本地prevLogIndex的任期号等于prevLogTerm时为true，其他为false</td>
</tr>
</tbody>
</table>
<ul>
<li>接受者本地的term（currentTerm）大于当前leader的term时，返回（currentTerm，false），此时的leader为过期leader，自动变为follower</li>
<li>当本地的prevLogIndex不等于prevLogTerm时，证明本机的日志与leader存在冲突，此时需要解决冲突，返回（term，false），leader会降低nextIndex,再次发送AppendEntries Rpc，重试直到成功</li>
<li>追加日志中不存在的新条目，删除冲突的条目</li>
<li>如果leaderCommit &gt; 本地已知的最高日志条目索引，则重置本地最高日志条目索引为leaderCommit与nextIndex的最小值。</li>
</ul>
<h4 id="安全性"><a href="#安全性" class="headerlink" title="安全性"></a>安全性</h4><p>选举限制</p>
<blockquote>
<p>当发起者term大于接受者本地term（currentTerm），并且接受者没投票给任何人，或者已经投票给此发起者，并且此时发起者的日志与接受者的日志状态一致或更新（先判断任期号，再判断索引值，越大越新），则返回（term，true），否则还是返回（term，false）</p>
</blockquote>
<p>提交之前任期内的日志条目</p>
<blockquote>
<p>为了保证一条被存储到大多数节点的日志条目不被未来领导人覆盖，需要保证每个leader需要至少提交一次日志，即半数以上被覆盖。</p>
</blockquote>
<p>故障容错性</p>
<ul>
<li>数据到达leader前：客户端重复提交即可</li>
<li>到达leader未复制到follower：未提交，也未返回，客户端重复提交即可</li>
<li>已复制到部分follower，未提交：重新选leader，并且新的leader拥有最新的提交，数据保证最终一致</li>
<li>已复制，未响应leader：客户端重新发送请求，因此要求rpc幂等，内部去重</li>
<li>leader已提交，follower未提交：重选leader，并且新的leader拥有最新的提交，数据保证最终一致</li>
<li>均已提交，未响应客户端：内部数据一致，幂等解决此问题</li>
<li>双leader：重新加入集群后，老leader会收到新的term成为follower并同步集群内新leader的数据</li>
</ul>
<p>因此在满足rpc幂等情况下，所有异常场景均能保持数据一致性。</p>
<h4 id="日志压缩"><a href="#日志压缩" class="headerlink" title="日志压缩"></a>日志压缩</h4><p>每个服务器独立创建快照（raft能基本保证每个节点的数据一致性），以下为raft快照的基本思路，即用一个快照存储当前的状态，并包含最后的索引位置和任期号，目的是为了支持下一次的一致性检查。<img src="/blog//eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/etcd源码阅读分析（一）/image-20210113001413169.png" alt="xx"></p>
<p><img src="/Users/lbin/workspace/hexo/source/_posts/etcd源码阅读分析（一）/image-20210113001413169.png" alt="image-20210113001413169"></p>
<p>快照的发送：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>领导人的任期号</td>
</tr>
<tr>
<td>leaderId</td>
<td>领导人的 Id，以便于跟随者重定向请求</td>
</tr>
<tr>
<td>lastIncludedIndex</td>
<td>快照中包含的最后日志条目的索引值</td>
</tr>
<tr>
<td>lastIncludedTerm</td>
<td>快照中包含的最后日志条目的任期号</td>
</tr>
<tr>
<td>offset</td>
<td>分块在快照中的字节偏移量</td>
</tr>
<tr>
<td>data[]</td>
<td>从偏移量开始的快照分块的原始字节</td>
</tr>
<tr>
<td>done</td>
<td>如果这是最后一个分块则为 true</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>结果</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>当前任期号（currentTerm），便于领导人更新自己</td>
</tr>
</tbody>
</table>
<ul>
<li>当本机term（currentTe人m）大于leader 的term时直接回复currentTerm</li>
<li>如果是第一个分块（offset 为 0）就创建一个新的快照</li>
<li>在指定偏移量写入数据</li>
<li>如果 done 是 false，则继续等待更多的数据</li>
<li>保存快照文件，并想用Leader</li>
<li>如果现存的日志条目与快照中最后包含的日志条目具有相同的索引值和任期号，则保留其后的日志条目并进行回复</li>
<li>使用快照重置状态机（并加载快照的集群配置）</li>
</ul>
<h3 id="raft的行为实现"><a href="#raft的行为实现" class="headerlink" title="raft的行为实现"></a>raft的行为实现</h3><p>以上拆分介绍了raft的三个字问题的解决方案，以及快照的实现机制，现根据解决方案针对leader，fallower，candidateId三种不同的角色进行行为与功能拆分。</p>
<h4 id="状态"><a href="#状态" class="headerlink" title="状态"></a>状态</h4><p>持久性状态（all）</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>currentTerm</td>
<td>服务器已知最新的任期（在服务器首次启动的时候初始化为0，单调递增）</td>
</tr>
<tr>
<td>votedFor</td>
<td>当前任期内收到选票的候选者id 如果没有投给任何候选者 则为空</td>
</tr>
<tr>
<td>log[]</td>
<td>日志条目;每个条目包含了用于状态机的命令，以及领导者接收到该条目时的任期（第一个索引为1）</td>
</tr>
</tbody>
</table>
<p>易失性状态（all）</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>commitIndex</td>
<td>已知已提交的最高的日志条目的索引（初始值为0，单调递增）</td>
</tr>
<tr>
<td>lastApplied</td>
<td>已经被应用到状态机的最高的日志条目的索引（初始值为0，单调递增）</td>
</tr>
</tbody>
</table>
<p>易失性状态 (leader)（选举后重新初始化）</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>nextIndex[]</td>
<td>对于每一台服务器，发送到该服务器的下一个日志条目的索引（初始值为领导者最后的日志条目的索引+1）</td>
</tr>
<tr>
<td>matchIndex[]</td>
<td>对于每一台服务器，已知的已经复制到该服务器的最高日志条目的索引（初始值为0，单调递增）</td>
</tr>
</tbody>
</table>
<p>RPC实现</p>
<p> <strong>AppendEntries RPC</strong></p>
<p>被领导者调用 用于日志条目的复制 同时也被当做心跳使用</p>
<p>参数：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>领导者的任期</td>
</tr>
<tr>
<td>leaderId</td>
<td>领导者ID 因此跟随者可以对客户端进行重定向（译者注：跟随者根据领导者id把客户端的请求重定向到领导者，比如有时客户端把请求发给了跟随者而不是领导者）</td>
</tr>
<tr>
<td>prevLogIndex</td>
<td>紧邻新日志条目之前的那个日志条目的索引</td>
</tr>
<tr>
<td>prevLogTerm</td>
<td>紧邻新日志条目之前的那个日志条目的任期</td>
</tr>
<tr>
<td>entries[]</td>
<td>需要被保存的日志条目（被当做心跳使用是 则日志条目内容为空；为了提高效率可能一次性发送多个）</td>
</tr>
<tr>
<td>leaderCommit</td>
<td>领导者的已知已提交的最高的日志条目的索引</td>
</tr>
</tbody>
</table>
<p>结果</p>
<table>
<thead>
<tr>
<th>返回值</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>当前任期,对于领导者而言 它会更新自己的任期</td>
</tr>
<tr>
<td>success</td>
<td>结果为真 如果跟随者所含有的条目和preLogIndex以及preLogTerm匹配上了</td>
</tr>
</tbody>
</table>
<p>接收者的实现：</p>
<ol>
<li>如果领导者的任期 小于 接收者的当前任期返回假 ,并且返回本地当前任期</li>
<li>在接收者日志中 如果能找到一个和preLogIndex以及prevLogTerm一样的索引和任期的日志条目 则返回真 否则返回假</li>
<li>如果一个已经存在的条目和新条目发生了冲突（因为索引相同，任期不同），那么就删除这个已经存在的条目以及它之后的所有条目 </li>
<li>追加日志中尚未存在的任何新条目</li>
<li>如果领导者的已知已经提交的最高的日志条目的索引 大于 接收者的已知已经提交的最高的日志条目的索引 则把 接收者的已知已经提交的最高的日志条目的索引 重置为 领导者的已知已经提交的最高的日志条目的索引 或者是 上一个新条目的索引 取两者的最小值</li>
</ol>
<p><strong>RequestVote RPC</strong>：</p>
<p>由候选人负责调用用来征集选票（5.2 节）</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>候选人的任期号</td>
</tr>
<tr>
<td>candidateId</td>
<td>请求选票的候选人的 Id</td>
</tr>
<tr>
<td>lastLogIndex</td>
<td>候选人的最后日志条目的索引值</td>
</tr>
<tr>
<td>lastLogTerm</td>
<td>候选人最后日志条目的任期号</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>返回值</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>term</td>
<td>当前任期号，以便于候选人去更新自己的任期号</td>
</tr>
<tr>
<td>voteGranted</td>
<td>候选人赢得了此张选票时为真</td>
</tr>
</tbody>
</table>
<p>接收者实现：</p>
<ol>
<li>如果<code>term &lt; currentTerm</code>返回 false 并返回currentTerm</li>
<li>如果 votedFor 为空或者为 candidateId，并且候选人的日志至少和自己一样新，那么就投票给他</li>
</ol>
<p><strong>所有服务器需遵守的规则</strong>：</p>
<p>所有服务器：</p>
<ul>
<li>如果<code>commitIndex &gt; lastApplied</code>，那么就 lastApplied 加一，并把<code>log[lastApplied]</code>应用到状态机中</li>
<li>如果接收到的 RPC 请求或响应中，任期号<code>term &gt; currentTerm</code>，那么就令 currentTerm 等于 term，并切换状态为跟随者</li>
</ul>
<p>跟随者：</p>
<ul>
<li>响应来自候选人和领导者的请求</li>
<li>如果在超过选举超时时间的情况之前没有收到<strong>当前领导人</strong>（即该领导人的任期需与这个跟随者的当前任期相同）的心跳/附加日志，或者是给某个候选人投了票，就自己变成候选人</li>
</ul>
<p>候选人：</p>
<ul>
<li>在转变成候选人后就立即开始选举过程<ul>
<li>自增当前的任期号（currentTerm）</li>
<li>给自己投票</li>
<li>重置选举超时计时器</li>
<li>发送请求投票的 RPC 给其他所有服务器</li>
</ul>
</li>
<li>如果接收到大多数服务器的选票，那么就变成领导人</li>
<li>如果接收到来自新的领导人的附加日志 RPC，转变成跟随者</li>
<li>如果选举过程超时，再次发起一轮选举</li>
</ul>
<p>领导人：</p>
<ul>
<li>一旦成为领导人：发送空的附加日志 RPC（心跳）给其他所有的服务器；在一定的空余时间之后不停的重复发送，以阻止跟随者超时</li>
<li>如果接收到来自客户端的请求：附加条目到本地日志中，在条目被应用到状态机后响应客户端</li>
<li>如果对于一个跟随者，最后日志条目的索引值大于等于 nextIndex，那么：发送从 nextIndex 开始的所有日志条目：<ul>
<li>如果成功：更新相应跟随者的 nextIndex 和 matchIndex</li>
<li>如果因为日志不一致而失败，减少 nextIndex 并且重试</li>
</ul>
</li>
<li>如果存在一个满足<code>N &gt; commitIndex</code>的 N，并且大多数的<code>matchIndex[i] ≥ N</code>成立，并且<code>log[N].term == currentTerm</code>成立，那么令 commitIndex 等于这个 N （防止半数以上的提交被新提交覆盖）</li>
</ul>

      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    
</div>
	  
	</div>
	

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    喵呜  |  喵呜
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/" title="etcd源码阅读分析（一）">http://eidolon_x.gitee.io/blog/2020/12/17/etcd源码阅读分析（一）/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
  <li class="post-copyright-license">
    并保留本声明和上方二维码。感谢您的阅读和支持！
  </li>
</ul>
      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/etcd/" rel="tag"># etcd</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/09/18/数据库基本操作/" rel="next" title="数据库基本操作">
                <i class="fa fa-chevron-left"></i> 数据库基本操作
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/1.jpg"
                alt="喵呜" />
            
              <p class="site-author-name" itemprop="name">喵呜</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index-1.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

			
			  <div class="site-state-item site-state-tags">
				<a href="/blog/tags/ || tags">
				  <span class="site-state-item-count">13</span>
				  <span class="site-state-item-name">标签</span>
				</a>
			  </div>
			

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#raft算法"><span class="nav-text">raft算法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#领袖选举"><span class="nav-text">领袖选举</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日志复制"><span class="nav-text">日志复制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#安全性"><span class="nav-text">安全性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日志压缩"><span class="nav-text">日志压缩</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#raft的行为实现"><span class="nav-text">raft的行为实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#状态"><span class="nav-text">状态</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">喵呜</span>

  
</div>

<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>


  <div class="powered-by">QQ  母胎solo </div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">微信：请勿撩骚 &mdash;  v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("C4C53NNHHx80rdEcr9XGvVER-gzGzoHsz", "onx6D9nlRn56BhlHoI3E08PQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  
  <script type="text/javascript" src="/blog/js/src/exturl.js?v=5.1.4"></script>


  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
